package cn.com.KnowNews.filter;

import javax.management.RuntimeMBeanException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

@WebFilter(filterName = "CharacterFilter")
public class CharacterFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        CharacterRequest characterRequest = new CharacterRequest(request);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    }


}

class CharacterRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;

    public CharacterRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    // 子类继承父类一定会覆写一些方法，此处用于重写getParameter()方法
    public String getParameter(String name) {
        // 调用被包装对象getParameter()方法，获得请求参数
        String value = super.getParameter(name);
        if (value == null) {
            return null;
        }
        String method = super.getMethod(); // 判断请求方式
        if ("get".equalsIgnoreCase(method)) {
            try {
                value = new String(value.getBytes("iso-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return value; // 解决乱码后返回结果
    }
}